<?php
namespace app\api\library;
 
use EasyWeChat\Factory;
use think\Cache;
use think\Config;
 
class Wechat
{
    protected $config = [];
    protected $siteConfig = [];
    protected $app = null;
    protected static $instance = null;
 
    /**
     * Wechat constructor.
     * @param $type
     */
    public function __construct($type = 'pay')
    {
        $siteConfig = Config::get('site');
        $this->siteConfig = $siteConfig;
        $this->config = array(
            'app_id'             => $siteConfig['appid'],
            'appid'              => $siteConfig['appid'],
            'mch_id'             => $siteConfig['mch_id'],
            'key'                => $siteConfig['secret'],
            'cert_path'          => $siteConfig['cert_path'],
            'key_path'           => $siteConfig['key_path'],
            'notify_url'         => request()->domain() . '/api' . $siteConfig['notify'],
        );
        $method = $type == 'pay' ? 'payment' : 'officialAccount';
        if ($type == 'officialAccount'){
        }
        $this->config = array_merge(array('secret' => $siteConfig['app_secret']),$this->config);
        $this->app = Factory::$method($this->config);
    }
 
    /**
     * @param string $type
     * @return static|null
     */
    public static function instance($type = 'pay')
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($type);
        }
        return self::$instance;
    }
 
    /**
     * 支付实例化
     * @return Pay
     */
    public function pay(){
        return new Pay();
    }
 
    /**
     * 退款实例化
     * @return Refund
     */
    public function refund(){
        return new Refund();
    }
 
    /**
     * 构建config
     * @param $apis
     * @param $uri
     * @return mixed
     */
    public function getBuildConfig($apis,$uri){
        $uri = strpos($uri,'amp;') !== false ? str_replace('amp;','',$uri) : $uri;
        $this->app->jssdk->setUrl(str_replace('amp;','',$uri));
        return $this->app->jssdk->buildConfig($apis,true);
    }
 
    /**
     * @param $prepayIds
     * @return mixed
     */
    public function getJsSdkConfig($prepayIds){
        return $this->app->jssdk->sdkConfig($prepayIds);
    }
 
    /**
     * 获取openid
     * @param $code
     * @return \Overtrue\Socialite\User
     */
    public function getOpenId($code){
        $secret = $this->config['secret'];
        $appid = $this->config['appid'];
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
 
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_TIMEOUT,30);
 
        $content = curl_exec($ch);
        $status = (int)curl_getinfo($ch,CURLINFO_HTTP_CODE);
        if ($status == 404) {
            return $status;
        }
        curl_close($ch);
        return json_decode($content,true);
    }
}